package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.UserDto;
import com.lkd.entity.Role;
import com.lkd.entity.User;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.RoleMapper;
import com.lkd.mapper.UserMapper;
import com.lkd.service.IUserService;
import com.lkd.utils.JwtUtil;
import com.lkd.vo.LoginUserVo;
import com.lkd.vo.PageBean;
import com.lkd.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaotao
 * @since 2025-10-18
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    // 注入全局密钥
    @Value("${jwt.secret-key}")
    private String secretKey;

    private final RoleMapper roleMapper;
    /**
     * 人员的搜索
     *
     * @param userDto
     * @return
     */
    @Override
    public PageBean<UserVo> search(UserDto userDto) {
        //1.设置分页参数
        Page<User> userPage = new Page<>(userDto.getPageIndex(), userDto.getPageSize());

        //2.设置业务参数
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(userDto.getUserName()), User::getUserName, userDto.getUserName());

        //3.执行分页查询
        Page<User> page = this.page(userPage, wrapper);

        List<UserVo> userVoList = page.getRecords().stream().map(user -> {
            //属性拷贝
            UserVo userVo = new UserVo();
            BeanUtil.copyProperties(user, userVo);

            //封装role对象
            Role role = roleMapper.selectById(user.getRoleId());
            userVo.setRole(role);

            return userVo;
        }).collect(Collectors.toList());

        //4.返回分页结果
        return new PageBean<>((int)page.getCurrent(), (int)page.getSize(), page.getPages(), page.getTotal(), userVoList);
    }

    /**
     * 登录
     *
     * @param loginName 登录名
     * @param password  密码
     * @return
     */
    @Override
    public LoginUserVo login(String loginName, String password) {
        //写登录的逻辑：根据loginName

        //1. 根据登录名查用户
        User user = lambdaQuery()
                .eq(User::getLoginName, loginName)
                .one();
        log.info("用户id:{}", user.getId());
        //用户不存在
        if(ObjectUtil.isNull(user)){
            log.info("用户不存在");
            throw new BusinessException("用户名或密码错误");
        }

        //密码错误
        //admin加密后：21232f297a57a5a743894a0e4a801fc3【测试用刘备，登录名admin666】
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            log.info("密码错误");
            throw new BusinessException("用户或密码错误");
        }

        //登录状态status=0,停用
        if (user.getStatus() == 0) {
            log.info("用户已停用");
            throw new BusinessException("用户已停用");
        }

        //登录成功，封装结果
        LoginUserVo loginUserVo = new LoginUserVo();
        //属性拷贝
        BeanUtil.copyProperties(user, loginUserVo);


        //调用工具类，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userName", user.getUserName());
        String token = JwtUtil.createJWT(secretKey, 10, claims);
        loginUserVo.setToken(token);
        loginUserVo.setUserId(user.getId());

        return loginUserVo;
    }
}
